package com.ym.manager.admin.merchant;

import com.ym.manager.sys.model.AdminUser;
import com.ym.utils.Common;
import com.ym.utils.DateUtil;
import com.ym.utils.ResultUtil;
import com.ym.web.bind.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//@Controller
//@RequestMapping("/merchant/")
public class MerchantController {

    @Autowired
    private MerchantManager merchantManager;
    @Autowired
    private MerchantServer merchantServer;

    @RequestMapping("detail")
    public String detail(Model model, @CurrentUser AdminUser adminUser){
        model.addAttribute("merchant",merchantManager.getMerchant(adminUser.getMerchant_id()));
        return "/merchant/detail";
    }

    /**
     * 保存店家信息
     * @param name
     * @param phone
     * @param address
     * @param adminUser
     * @return
     */
    @RequestMapping("saveExpressInfo")
    @ResponseBody
    public String saveExpressInfo(@RequestParam(defaultValue = "") String name,
                                  @RequestParam(defaultValue = "") String phone,
                                  @RequestParam(defaultValue = "") String address,
                                  @CurrentUser AdminUser adminUser){
        Map<String, Object> result = ResultUtil.result();
        if(Common.isEmpty(name) || Common.isEmpty(phone) || Common.isEmpty(address)){
            result.put("code",400);
            result.put("msg","参数异常");
            return ResultUtil.toJSON(result);
        }
        try {
            Map<String,Object> expressMap = new HashMap<String, Object>(){{
               put("merchant_id",adminUser.getMerchant_id());
               put("update_user",adminUser.getName());
               put("update_time", DateUtil.getDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
               put("name",name);
               put("phone",phone);
               put("address",address);
            }};
            int i = merchantServer.saveExpressInfo(adminUser.getMerchant_id(),expressMap);
            if(i>0){
                merchantManager.load();
                result.put("code",200);
                result.put("msg","保存成功");
            }else{
                result.put("code",500);
                result.put("msg","更新失败，请联系管理员");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultUtil.toJSON(result);
    }
}
